package com.fingard.dsp.bank.directbank.fubon01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IBalance;
import com.fingard.dsp.bank.reqrespobj.balance.Req7505HisBalQry;
import com.fingard.dsp.bank.reqrespobj.balance.Req7506BalQry;
import com.fingard.dsp.bank.reqrespobj.balance.RetAts7505HisBalQry;
import com.fingard.dsp.bank.reqrespobj.balance.RetAts7506BalQry;
import com.fingard.dsp.bank.reqrespobj.balance.detail.RetAtsBalDetail;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.text.DecimalFormat;
import java.util.Date;

public class FUBON01Balance extends FUBON01Base implements IBalance {
    @Override
    public RetAts7506BalQry d_7506_BalQry(Req7506BalQry p_req7506) throws Exception {
        //余额查询返回ATS的对象
        RetAts7506BalQry retAts = new RetAts7506BalQry(p_req7506.reqHeader);
        retAts.writeStart();//写返回ATS的统一头部信息
        try {
            WriteBankLogLn("进入余额查询处理类 ");
            while (p_req7506.readRecord()) {
                //全局流水
                String transSeqId = p_req7506.reqHeader.transSeqID;
                transSeqId = bankFront.corpNo + "01" + "301010" + Format.Date8Format.format(new Date()) + "00" + transSeqId.substring(transSeqId.length() - 8, transSeqId.length());

                XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                FUBON01Header fubon01Header = new FUBON01Header();
                fubon01Header.ServiceCode = "06002010001";//服务唯一标识，由EAI提供
                fubon01Header.ServiceScene = "01";//服务场景
                fubon01Header.InitiatorId = "203010";//发起方系统编号
                fubon01Header.ServiceId = "301010";//服务系统编号
                fubon01Header.TranDate = Format.Date8Format.format(new Date());//前台交易日期 YYYYMMDD
                fubon01Header.TranTime = Format.Time6Format.format(new Date());//前台交易时间 hhmmss
                fubon01Header.OrgConSeqNo = transSeqId;//发起方流水号 全局流水号
                fubon01Header.ConsumerSeqNo = transSeqId;//消费方流水号 调用方产生流水号
                fubon01Header.FileFlag = "0";//文件标识 1-有文件，0-无文件
                writeCommonHeader(xmlWriter, fubon01Header);

                xmlWriter.writeStartElement("Body");
                xmlWriter.writeElementString("QueryType", "3");//？？查询关键字类型
                xmlWriter.writeElementString("AccountType", "CA");//帐户类型
                String actNum = p_req7506.readedDetail.actNum;
                actNum = String.format("%1$-27s", actNum);
                xmlWriter.writeElementString("QueryParameter", actNum + convertCurToBank(p_req7506.readedDetail.actCur));//查询关键字
                xmlWriter.writeElementString("MaxReNum", "25");//最大的数据笔数
                xmlWriter.writeElementString("PageNo", "1");//查询页号
                xmlWriter.writeElementString("LastPageLineAcct", "");//上页最末行帐号
                xmlWriter.writeElementString("LastPageLineCcy", "");//上页最末行币种
                xmlWriter.writeElementString("LastPageLineMark", "");//上页最末行钞汇
                xmlWriter.writeEndDocument();


                //gxp通讯报文头
                fubon01Header.glbTrSeq = transSeqId;
                fubon01Header.recvId = "CORE";//服务方ID
                String gxpHeader = writeGxpHeader(fubon01Header, xmlWriter.toXmlString());


                RetAts7506BalQry errRetAts = new RetAts7506BalQry(p_req7506.reqHeader);//如果异常则返回该结果给ATS
                errRetAts.writeStart();//写返回ATS的统一头部信息
                errRetAts.writeRespCode("-1");
                String[] tmpRetBkStr = sendToBankQry(gxpHeader, gxpHeader + xmlWriter.toXmlString());
//                String[] tmpRetBkStr = {"", "<service><GapsAppHead><RespCode>000000</RespCode><RespMsg>交易成功</RespMsg><OrgConSeqNo>20200302155147558</OrgConSeqNo><ConsumerSeqNo>446282</ConsumerSeqNo><FileFlag>0</FileFlag><TranDate>20200302</TranDate><TranTime>155149</TranTime><TellerNo>0000000000</TellerNo><BranchId>0000000000</BranchId><TellerPassword></TellerPassword><TellerLevel></TellerLevel><TellerType></TellerType><ApprFlag></ApprFlag><ApprTellerArray><ApprTellerNo></ApprTellerNo><ApprBranchId></ApprBranchId><ApprTellerLevel></ApprTellerLevel><ApprTellerType></ApprTellerType></ApprTellerArray><AuthTellerInfo><AuthTellerNo></AuthTellerNo><AuthBranchId></AuthBranchId><AuthTellerPassword></AuthTellerPassword><AuthTellerLevel></AuthTellerLevel><AuthTellerType></AuthTellerType></AuthTellerInfo><AuthFlag></AuthFlag><BckFld1></BckFld1><BckFld2></BckFld2><BckFld3></BckFld3><BckFld4></BckFld4><BckFld5></BckFld5></GapsAppHead><Body><QueryType>3</QueryType><QueryParameter>10000020100003970          RMB</QueryParameter><EOF></EOF><PageNo>00</PageNo><ReNum>01</ReNum><AcctBalanceList><AcctBalance><Acct>10000020100003970</Acct><Ccy>RMB</Ccy><Mark></Mark><Amt>00901124017649+</Amt><BookAmt>00901124017649+</BookAmt><AvaibleAmt>00901124017649+</AvaibleAmt><FDSql></FDSql><FDLimit>000</FDLimit><FDType></FDType><EName>RLQHZPRIVYMVKGYEXVXXZZHDNLBMFDWWTFI</EName><CName>福建东丽鲁能纸业股份有限</CName><AccType>B</AccType><AOCode>100N0598</AOCode><AOBranch>100</AOBranch><ACC-FTZ></ACC-FTZ><SALARY-IND></SALARY-IND><CARDNO></CARDNO></AcctBalance></AcctBalanceList></Body></service>"};
                if (tmpRetBkStr[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpRetBkStr[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String returnCode = tmpBkReader.getFirstText("/service/GapsAppHead/RespCode");
                        String returnMsg = tmpBkReader.getFirstText("/service/GapsAppHead/RespMsg");
                        RetAtsBalDetail tmpRetDetail = new RetAtsBalDetail();
                        if (returnCode != null && "000000".equals(returnCode)) {
                            tmpRetDetail.respCode = "0";
                            tmpRetDetail.respInfo = "余额查询成功！";
                            tmpRetDetail.actNum = tmpBkReader.getFirstText("/service/Body/AcctBalanceList/AcctBalance/Acct");
                            tmpRetDetail.actCur = convertCurToATS(tmpBkReader.getFirstText("/service/Body/AcctBalanceList/AcctBalance/Ccy"));//币种
                            String currBal = tmpBkReader.getFirstText("/service/Body/AcctBalanceList/AcctBalance/Amt");//当前余额，最后一位是符号位，无小数
                            String availBal = tmpBkReader.getFirstText("/service/Body/AcctBalanceList/AcctBalance/AvaibleAmt");//可用余额
                            currBal = currBal.substring(0, currBal.length() - 1);
                            availBal = availBal.substring(0, availBal.length() - 1);
                            DecimalFormat df = new DecimalFormat();
                            String style = "0.00";
                            df.applyPattern(style);
                            tmpRetDetail.currBal = df.format(Double.parseDouble(currBal) / 100.00);
                            tmpRetDetail.availBal = df.format(Double.parseDouble(availBal) / 100.00);
                            retAts.writeRetDetail(tmpRetDetail, p_req7506.isBatch);
                        } else {
                            String tmpreturnMsg = StringHelper.isNullOrEmpty(getBankConfig().getMapValueByKey("fail_code", returnCode)) ? returnMsg : getBankConfig().getMapValueByKey("fail_code", returnCode);
                            errRetAts.writeRespInfo("错误代码：" + returnCode + ";错误信息：" + tmpreturnMsg);
                            errRetAts.writeEnd();
                            return errRetAts;
                        }
                    } else {
                        errRetAts.writeRespInfo(tmpSbMsg.toString());
                        errRetAts.writeEnd();
                        return errRetAts;
                    }
                } else {
                    errRetAts.writeRespInfo(tmpRetBkStr[1]);
                    errRetAts.writeEnd();
                    return errRetAts;
                }

            }
        } catch (Exception e) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo("余额查询异常!");
            e.printStackTrace();
            WriteBankLogLn("余额查询异常：" + e.getMessage());
        }
        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAts7505HisBalQry d_7505_BalQry(Req7505HisBalQry p_req7505) throws Exception {
        return null;
    }
}
